// pages/me/address/addedit/addedit.js
import userAddr from '../../../../model/userAddr'
import util from '../../../../utils/util'
let msg
Page({
  data: {
    //表单数据
    id: '',
    title: '',
    nick: '',
    phone: '',
    addrId: '',
    area: '',
    location: '',
    comy: '',
    ridgepole: '',
    door: '',
    detail: '',
    x: '',
    y: '',
    sex: '',
    isFirst: 0,
    options: [],
    background: 'rgba(0,0,0)',

    addrOptions: [],
    multiIndex: [0, 0]
  },

  /**
   * 地址三级联动下拉选择
   * @param {*} e 
   */
  pickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    let multiIndex = e.detail.value
    let comy = this.data.addrOptions[0][multiIndex[0]].name
    let ridgepole = this.data.addrOptions[1][multiIndex[1]].name
    this.setData({
      multiIndex: e.detail.value,
      comy: comy,
      ridgepole: ridgepole
    })

  },
  /**
   * 多选列改变
   * @param {*} e 
   */
  pickerColumnChange: function (e) {
    let column = e.detail.column
    let index = e.detail.value
    let multiIndex = this.data.multiIndex
    let addrOptions = this.data.addrOptions
    //如果当前节点不是最后一列，则默认获取后面列的第一个选项的
    for (let level = column; level < 2; level++) {
      let node = addrOptions[level][0]
      multiIndex[level] = [0]
      if (level == column) {
        node = addrOptions[level][index]
        multiIndex[level] = index
      }

      //如果当前改变的节点不是最终节点，则更新子节点
      if (level < 1 && node) {
        addrOptions[level + 1] = node.children
      }

      this.setData({
        addrOptions: addrOptions,
        multiIndex: multiIndex
      })
    }

  },

  /**
   * 联系电话输入
   * @param {*} e 
   */
  phoneInput: function (e) {
    this.setData({
      phone: e.detail.value
    })
  },
  /**
   * 联系人输入
   * @param {*} e 
   */
  nickInput: function (e) {
    this.setData({
      nick: e.detail.value
    })
  },
  /**
   * 详细地址输入
   * @param {*} e 
   */
  detailInput: function (e) {
    this.setData({
      door: e.detail.value
    })
  },

  /**
   * 设置默认地址
   * @param {*} e 
   */
  checkboxChange(e) {
    let isFirst = this.data.isFirst === 1 ? 0 : 1; // 切换 isFirst 变量的值
    this.setData({
      isFirst: isFirst
    });
  },
  /**
   * 表单提交
   * @param {*} e 
   */
  submit: function (e) {

    if (!this.data.options | this.data.options.length == 0) {
      msg && msg.show({
        text: '该地区尚未开通服务，敬请期待'
      })
      return
    }

    if (!this.data.nick) {
      msg && msg.show({
        text: '请填写称呼'
      })
      return
    }
    //手机号格式校验
    const phoneReg = /^1[3456789]\d{9}$/;
    if (!phoneReg.test(this.data.phone)) {
      msg && msg.show({
        text: '手机号格式不正确'
      })
      return
    }
    if (!this.data.area) {
      msg && msg.show({
        text: '请选择地区'
      })
      return
    }

    let comy = this.data.comy
    let ridgepole = this.data.ridgepole

    if (!comy | !ridgepole) {
      msg && msg.show({
        text: '请选择小区和楼栋'
      })
      return
    }

    if (!this.data.door) {
      msg && msg.show({
        text: '请填写房号或详细地址'
      })
      return
    }

    let addrId = this.data.addrOptions[1][this.data.multiIndex[1]].id
    let addrDetail = comy + " - " + ridgepole + " - " + this.data.door

    let req = {
      detail: addrDetail,
      addrId: addrId,
      nick: this.data.nick,
      phone: this.data.phone,
      area: this.data.area,
      comy: comy,
      ridgepole: ridgepole,
      door: this.data.door,
      isFirst: this.data.isFirst
    }
    if (this.data.id) {
      req.id = this.data.id
      userAddr.edit(req, res => {
        if (res.code == 200) {
          wx.navigateBack(1)
          msg && msg.show({
            text: '地址更新成功'
          })
        } else {
          msg && msg.show({
            text: res.msg
          })
        }
      })
    } else {
      userAddr.addOne(req, res => {
        if (res.code == 200) {
          wx.navigateBack(1)
          msg && msg.show({
            text: '地址保存成功'
          })
        } else {
          msg && msg.show({
            text: res.msg
          })
        }
      })
    }
  },
  /**
   * 获取地址详情
   * @param {*} id 
   */
  getDetail(id) {
    const req = {
      id: id
    }
    userAddr.detail(req, res => {
      if (res.code == 200) {
        const data = res.data
        this.setData({
          id: data.id,
          nick: data.nick,
          phone: data.phone,
          area: data.area,
          comy: data.comy,
          ridgepole: data.ridgepole,
          door: data.door,
          isFirst: data.isFirst,
          addrId: data.addrId,
          pickerValue: [data.comy, data.ridgepole]
        })

        this.getOptions({
          area: data.area
        })
      } else {
        msg && msg.show({
          text: res.msg
        })
      }
    })

  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const id = options.itemId
    if (id) {
      this.getDetail(id)
      return
    }
  },
  /**
   * 获取地址选项
   * @param {*} e 
   */
  getOptions(req) {
    let _this = this
    //根据定位地址获取地址选择列表
    userAddr.itemList(req, res => {
      if (res.code == 200) {
        let options = res.data

        if (!Array.isArray(options) || options.length === 0) {
          this.setData({
            options: [],
            addrOptions: []
          })
          return
        }

        let addrOptions = []
        addrOptions.push(options)
        addrOptions.push(options[0].children)


        // 根据保存的省份和城市找到对应的索引
        let comy = _this.data.comy
        let ridgepole = _this.data.ridgepole

        if (comy && ridgepole) {
          let comyIndex = addrOptions[0].findIndex(item => item.name === comy);
          let ridgIndex = addrOptions[1].findIndex(item => item.name === ridgepole);

          let multiIndex = _this.data.multiIndex
          if (comyIndex === -1 | ridgIndex === -1) {
            multiIndex = []
          } else {
            multiIndex[0] = comyIndex
            multiIndex[1] = ridgIndex
          }
          // 设置选择器的value属性回显数据
          _this.setData({
            multiIndex: multiIndex
          });
        }
        _this.setData({
          options: options,
          addrOptions: addrOptions
        })
      }
    })
  },

  /**
   * 点击输入框触发选择位置事件
   * @param {*} e 
   */
  chooseLocation: function (e) {
    var that = this;
    wx.chooseLocation({
      success: function (res) {
        // 获取选中位置的地址信息
        var area = util.extAddr(res.address);

        // 将地址信息回显到输入框中
        that.setData({
          area: area,
          detail: res.address,
          options: [],
          addrId: '',
          comy: '',
          ridgepole: '',
          multiIndex: [],
          x: res.longitude,
          y: res.latitude
        });
        that.getOptions({
          area: area
        })
      },
      complete: function (res) {}
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    msg = this.selectComponent("#msg")
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})